package com.xiangxiangjd.kj.papersstar.controller.api;


import cn.afterturn.easypoi.entity.ImageEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiangxiangjd.kj.papersstar.bean.Answer;
import com.xiangxiangjd.kj.papersstar.bean.Questionnaire;
import com.xiangxiangjd.kj.papersstar.bean.QuestionnaireUser;
import com.xiangxiangjd.kj.papersstar.bean.Topic;
import com.xiangxiangjd.kj.papersstar.controller.BaseController;
import com.xiangxiangjd.kj.papersstar.controller.helper.$;
import com.xiangxiangjd.kj.papersstar.controller.model.ApiResultModel;
import com.xiangxiangjd.kj.papersstar.utils.echarts.JfreeUtil;
import com.xiangxiangjd.kj.papersstar.utils.echarts.WordUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 肖守凯
 * @since 2021-01-26
 */
@Controller
@RequestMapping("/api/questionnaireUser")
@Slf4j
public class QuestionnaireUserApi extends BaseController {


    /**
     * 提交调查问卷
     */
    @RequestMapping(value = "submitQuestionnaire")
    @ResponseBody
    public ApiResultModel submitQuestionnaire(@RequestBody QuestionnaireUser questionnaireUser) {
        return questionnaireService.submitQuestionnaire(questionnaireUser);
    }

    /**
     * 获取用户已经回答的问题
     */
    @ResponseBody
    @RequestMapping(value = "getQuestionnaireAnswered/{questionnaireId}")
    public ApiResultModel getQuestionnaireAnswered(@PathVariable("questionnaireId") String questionnaireId) {

        //查询已经回答的用户
        Questionnaire questionnaire = questionnaireService.getQuestionnaireAnswered(questionnaireId);


        return $.success(questionnaire);
    }


    private static final String URL_TEMPLATE = "D:\\project\\papers-star\\src\\main\\resources\\static\\demo1.docx";//word模板相对路径
    private static final String URL_FILE = "D:\\fileServer\\";//word生成路径

    /**
     * 下载导入的ex 的表格
     */
    @RequestMapping(value = "/getEcharts/{questionnaireId}")
    public void getEcharts(@PathVariable("questionnaireId") String questionnaireId, HttpServletResponse response, HttpServletRequest request) {
        response.setContentType("application/octet-stream");

        FileInputStream fis = null;

        //总数组
        HashMap<String, Object> map = new HashMap<>(16);
        //获取所有的问题
        QueryWrapper topicQW = new QueryWrapper();
        topicQW.eq("questionnaire_id", questionnaireId);
        List<Topic> topicList = topicService.list(topicQW);

        List<HashMap> list = new ArrayList<>();

        //遍历所得问题
        for (int i = 0; i < topicList.size(); i++) {

            //模拟饼状图数据
            HashMap<String, Integer> datas = new HashMap<>(16);

            //获取问题的所有答案
            QueryWrapper answerQW = new QueryWrapper();
            answerQW.eq("topic_id", topicList.get(i).getId());
            List<Answer> answerList = answerService.list(answerQW); //获取问题的所有答案


            answerList.forEach((answer) -> {
                QueryWrapper userAnswerQW = new QueryWrapper();

                userAnswerQW.eq("answer_id", answer.getId());
                List userAnswerList = userAnswerService.list(userAnswerQW);

                datas.put(answer.getAnswerKey(), userAnswerList.size());


            });
            ImageEntity imageEntity = JfreeUtil.pieChart("测试", datas, 500, 300);

            HashMap<String, Object> temp = new HashMap<>(topicList.size());
            temp.put("line", i + 1);
            temp.put("title", topicList.get(i).getTopicTitle());
            temp.put("image", imageEntity);
            list.add(temp);

        }
        //文件详情
        Questionnaire byid = questionnaireService.getById(questionnaireId);


        map.put("questionnaire", list);
        map.put("image",list.get(0).get("imageEntity"));

        map.put("string","输入一个字符串");


        //word模板相对路径、word生成路径、word生成的文件名称、数据源
        WordUtil.exportWord(URL_TEMPLATE, URL_FILE, byid.getQuestionnaireTitle() + ".docx", map);


        //获取名字

        try {
            File file = new File(URL_FILE + byid.getQuestionnaireTitle() + ".docx");
            System.out.println("问卷名称:" + file.getName());

            fis = new FileInputStream(file);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            String formFileName = file.getName();
            formFileName = new String(formFileName.getBytes("UTF-8"), "ISO-8859-1");
            response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", formFileName));
            IOUtils.copy(fis, response.getOutputStream());
            response.flushBuffer();
            //修改数据库 下载次数


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    private HashMap<String, Object> getDataMap(String questionnaireId) {


        HashMap<String, Object> map = new HashMap<>(4);

        //模拟饼状图数据
        HashMap<String, Integer> datas = new HashMap<>(3);
        datas.put("一号", 10);
        datas.put("二号", 20);
        datas.put("三号", 40);
        ImageEntity imageEntity = JfreeUtil.pieChart("测试", datas, 500, 300);
        map.put("picture", imageEntity);

        //模拟其它普通数据
        map.put("username", "张三");
        map.put("date", "2019-10-10");
        map.put("desc", "测试");
        map.put("boo", true);

        //模拟表格数据
        ArrayList<HashMap<String, String>> list = new ArrayList<>(2);
        HashMap<String, String> temp = new HashMap<>(3);
        temp.put("sn", "1");
        temp.put("name", "第一个人");
        temp.put("age", "23");
        list.add(temp);
        temp = new HashMap<>(3);
        temp.put("sn", "2");
        temp.put("name", "第二个人");
        temp.put("age", "24");
        list.add(temp);
        map.put("personlist", list);
        return map;
    }

}
